<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\DiyForm;
use App\Services\MiniProgramService;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class DiyFormController extends AdminController
{
    public function index(Content $content)
    {
        $slug = request()->input('mini_type');

        $tab = Tab::make();
        $tab->add('自定义表单', $this->grid(), true);
        $tab->addLink('表单提交内容', admin_route('diy_form_content.index', ['mini_type' => $slug]));

        return $content->body($tab->withCard());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new DiyForm(), function (Grid $grid) {
            $map = getAuthMiniProgramMap(Admin::user()->id);
            $grid->model()->whereIn('mini_type', array_keys($map))->orderByDesc('id');

            $grid->column('id');
            $grid->column('mini_type')->display(function ($miniType) use ($map) {
                return $miniType ? $map[$miniType] : '';
            });
            $grid->column('name');
            $grid->column('status')->switch();
            $grid->column('mini_app_short_link', '小程序短链')->display('查看')->modal(function ($modal) {
                $modal->title('小程序短链');
                $modal->icon('');

                $id = $this->id;
                $link = $this->mini_app_short_link;

                return admin_view('admin.diy_form.short_link', compact('id', 'link'));
            });
            $grid->column('created_at');
            $grid->column('updated_at');

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append('<a style="margin-right:5px" href="' . admin_route('diy_form_content.index', ['diy_form_id' => $actions->row->id]) . '">已提交内容</a>');
            });

            $grid->filter(function (Grid\Filter $filter) use ($map) {
                $filter->panel();
                $filter->expand();

                $filter->equal('id')->width(2);
                $filter->like('name')->width(2);
                $filter->equal('mini_type')->select($map)->width(2);
                $filter->between('created_at')->datetime()->width(3);
            });

            $grid->disableViewButton();
        });
    }

    public function store()
    {
        $validator = Validator::make(request()->post(), [
            'id'        => 'nullable',
            'mini_type' => 'required',
            'name'      => 'required|string',
            'content'   => 'nullable|string',
            'img'       => 'nullable|string',
            'status'    => 'required|in:0,1',
            'config'    => 'required|array',

            'config.*.label'          => 'required|string',
            'config.*.type'           => 'required|string',
            'config.*.is_required'    => 'nullable|in:0,1',
            'config.*.text_limit'     => 'nullable|integer',
            'config.*.textarea_limit' => 'nullable|integer',
            'config.*.rows'           => 'nullable|integer',
            'config.*.upload_num'     => 'nullable|integer',
            'config.*.options'        => 'nullable|array',
        ], [
            'mini_type.required'      => '小程序不能为空',
            'name.required'           => '名称不能为空',
            'status.required'         => '状态不能为空',
            'status.in'               => '状态参数错误',
            'config.required'         => '表单配置不能为空',
            'config.array'            => '表单配置参数错误',
            'config.*.label.required' => '标题名称不能为空',
            'config.*.type.required'  => '类型不能为空',
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => false, 'msg' => $validator->errors()->first()]);
        }

        $data = $validator->validate();

        foreach ($data['config'] as $item) {
            if (in_array($item['type'], ['select', 'radio', 'checkbox']) && !($item['options'] ?? [])) {
                return response()->json(['status' => false, 'msg' => $item['label'] . '选项不能为空']);
            }
        }

        $id = $data['id'] ?? 0;

        unset($data['id']);

        $data['img'] = (string)($data['img'] ?? '');
        $data['content'] = (string)($data['content'] ?? '');
        $data['config'] = json_encode($data['config'] ?? []);

        if ($id) {
            $ret = \App\Models\DiyForm::where('id', $id)->update($data);
        } else {
            $ret = \App\Models\DiyForm::create($data);
        }

        return response()->json(
            $ret ?
                ['status' => true, 'msg' => '保存成功'] :
                ['status' => false, 'msg' => '保存失败'],
        );
    }

    public function edit($id, Content $content)
    {
        $info = \App\Models\DiyForm::find($id);
        $miniType = getAuthMiniProgramMap(Admin::user()->id);

        return $content
            ->translation($this->translation())
            ->title($this->title())
            ->description($this->description()['edit'] ?? trans('admin.edit'))
            ->body(view('admin.diy_form.form', ['info' => $info, 'miniType' => $miniType]));
    }

    public function update($id)
    {
        \App\Models\DiyForm::where('id', $id)->update([
            'status' => request()->input('status')
        ]);

        return Admin::json()->success('更新成功');
    }

    public function destroy($id)
    {
        $id = explode(',', $id);
        \App\Models\DiyForm::whereIn('id', $id)->delete();

        return Admin::json()->success('删除成功')->refresh();
    }

    protected function form()
    {
        $miniType = getAuthMiniProgramMap(Admin::user()->id);

        return view('admin.diy_form.form', ['miniType' => $miniType]);
    }

    public function generateShortLink(Request $request)
    {
        $id = $request->input('id');
        if (!$id) return response()->json(['status' => false, 'msg' => 'id不能为空']);

        $info = \App\Models\DiyForm::find($id);
        if (!$info) return response()->json(['status' => false, 'msg' => '信息不存在']);

        if (!$info->mini_type) return response()->json(['status' => false, 'msg' => '请先归属小程序']);

        $ret = app(MiniProgramService::class)->getShortLink(
            $info->mini_type,
            'pages/questionnaire/index?id=' . $id,
            $info->name ?: '',
        );

        if (!$ret['status']) return response()->json(['status' => false, 'msg' => $ret['msg']]);

        $link = $ret['data'] ?? '';
        if (!$link) return response()->json(['status' => false, 'msg' => '生成短链失败']);

        $info->update(['mini_app_short_link' => $link]);
        return response()->json(['status' => true, 'data' => $link, 'msg' => '操作成功']);
    }
}
